package com.baitai.system.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.List;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baitai.common.core.domain.AjaxResult;
import com.baitai.common.core.domain.entity.SysUser;
import com.baitai.common.utils.AliPayUtil;
import com.baitai.common.utils.DateUtils;
import com.baitai.common.utils.OSSClientUtil;
import com.baitai.system.domain.*;
import com.baitai.system.domain.vo.PrizeProductInfo;
import com.baitai.system.domain.vo.ProductInfoVo;
import com.baitai.system.domain.vo.SysUserPrizesVo;
import com.baitai.system.mapper.SysUserMapper;
import com.baitai.system.mapper.SysUserPrizesMapper;
import com.baitai.system.service.IProductOrdersService;
import com.baitai.system.service.ISysConfigService;
import com.baitai.system.service.IUserPointsLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Random;

import com.baitai.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.baitai.system.mapper.ProductInfoMapper;
import com.baitai.system.service.IProductInfoService;

import javax.imageio.ImageIO;

/**
 * 商品详情Service业务层处理
 *
 * @author xx
 * @date 2024-07-17
 */
@Service
public class ProductInfoServiceImpl implements IProductInfoService {
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private IProductOrdersService productOrdersService;
    @Autowired
    private IUserPointsLogService pointsLogService;
    @Autowired
    private SysUserPrizesMapper prizesMapper;

    @Value("${pay.ali.alipay-public-key}")
    private String alipayPublicKey;

    @Value("${pay.ali.private-key}")
    private String privateKey;

    @Value("${pay.ali.appid}")
    private String appid;

    @Value("${pay.ali.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.endpoint}")
    private String OSSEndpoint;

    @Value("${aliyun.oss.access-id}")
    private String OSSAccessKeyId;

    @Value("${aliyun.oss.access-key}")
    private String OSSAccessKeySecret;

    @Value("${aliyun.oss.dir}")
    private String OSSFiledir;

    @Value("${aliyun.oss.bucket}")
    private String OSSBucketName;
    @Value("${aliyun.oss.previewUrl}")
    private String previewUrl;


    /**
     * 查询商品详情
     *
     * @param id 商品详情主键
     * @return 商品详情
     */
    @Override
    public ProductInfo selectProductInfoById(Long id) {
        ProductInfo info = productInfoMapper.selectProductInfoById(id);
        if (StringUtils.isNotNull(info.getProductFileList())) {
            try {
                OSSClientUtil ossClientUtil = new OSSClientUtil();
                ossClientUtil.init(OSSEndpoint, OSSAccessKeyId, OSSAccessKeySecret, OSSFiledir, OSSBucketName);
                for (ProductFile productFile : info.getProductFileList()) {
                    if (StringUtils.isEmpty(productFile.getImageHeight()) || StringUtils.isEmpty(productFile.getImageWidth())) {
                        String fileUrl = productFile.getUrl();
                        fileUrl = fileUrl.substring(fileUrl.indexOf("/") + 1);
                        fileUrl = OSSFiledir + fileUrl.substring(fileUrl.indexOf("/"));
//                    File picture = new File(fileUrl);
                        BufferedImage sourceImg = ImageIO.read(ossClientUtil.getInputStream(fileUrl));
                        String imageWidth = sourceImg.getWidth() + "";
                        String imageHeight = sourceImg.getHeight() + "";
                        productFile.setImageWidth(imageWidth);
                        productFile.setImageHeight(imageHeight);
                        if (StringUtils.isNotEmpty(imageWidth) && StringUtils.isNotEmpty(imageHeight)) {
                            productInfoMapper.updateProductFile(productFile);
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("读取图片失败获取宽高错误");
            }
        }
        return info;
    }

    /**
     * 查询商品详情列表
     *
     * @param productInfo 商品详情
     * @return 商品详情
     */
    @Override
    public List<ProductInfo> selectProductInfoList(ProductInfo productInfo) {
        return productInfoMapper.selectProductInfoList(productInfo);
    }

    @Override
    public List<ProductInfo> appList(ProductInfo productInfo) {
        List<ProductInfo> result = productInfoMapper.appList(productInfo);
        // 创建一个Random对象
        Random random = new Random();
        for (ProductInfo info : result) {
            // 生成一个95到100之间的随机数（包括95和100）
            int randomNumber = random.nextInt(100 - 95) + 95;
            info.setFavorableRate(randomNumber + "%");
        }
        return result;
    }

    /**
     * 新增商品详情
     *
     * @param productInfo 商品详情
     * @return 结果
     */
    @Transactional
    @Override
    public int insertProductInfo(ProductInfo productInfo) {
        productInfo.setCreateTime(DateUtils.getNowDate());
        int rows = productInfoMapper.insertProductInfo(productInfo);
        insertProductFile(productInfo);
        return rows;
    }

    /**
     * 修改商品详情
     *
     * @param productInfo 商品详情
     * @return 结果
     */
    @Transactional
    @Override
    public int updateProductInfo(ProductInfo productInfo) {
        productInfo.setUpdateTime(DateUtils.getNowDate());
        productInfoMapper.deleteProductFileByProductId(productInfo.getId());
        insertProductFile(productInfo);
        return productInfoMapper.updateProductInfo(productInfo);
    }

    /**
     * 批量删除商品详情
     *
     * @param ids 需要删除的商品详情主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProductInfoByIds(Long[] ids) {
        productInfoMapper.deleteProductFileByProductIds(ids);
        return productInfoMapper.deleteProductInfoByIds(ids);
    }

    /**
     * 删除商品详情信息
     *
     * @param id 商品详情主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProductInfoById(Long id) {
        productInfoMapper.deleteProductFileByProductId(id);
        return productInfoMapper.deleteProductInfoById(id);
    }

    /**
     * 新增商品图片信息
     *
     * @param productInfo 商品详情对象
     */
    public void insertProductFile(ProductInfo productInfo) {
        List<ProductFile> productFileList = productInfo.getProductFileList();
        Long id = productInfo.getId();
        if (StringUtils.isNotNull(productFileList)) {
            List<ProductFile> list = new ArrayList<ProductFile>();
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.init(OSSEndpoint, OSSAccessKeyId, OSSAccessKeySecret, OSSFiledir, OSSBucketName);
            for (ProductFile productFile : productFileList) {
                try {
                    String fileUrl = productFile.getUrl();
                    fileUrl = fileUrl.substring(fileUrl.indexOf("/") + 1);
                    fileUrl = OSSFiledir + fileUrl.substring(fileUrl.indexOf("/"));
                    BufferedImage sourceImg = ImageIO.read(ossClientUtil.getInputStream(fileUrl));
                    String imageWidth = sourceImg.getWidth() + "";
                    String imageHeight = sourceImg.getHeight() + "";
                    productFile.setImageWidth(imageWidth);
                    productFile.setImageHeight(imageHeight);
                } catch (Exception e) {
                    System.out.println("读取图片失败获取宽高错误");
                }
                productFile.setProductId(id.toString());
                list.add(productFile);
            }
            if (list.size() > 0) {
                productInfoMapper.batchProductFile(list);
            }
        }
    }

    @Transactional
    @Override
    public String conversionProduct(Long userId, ProductInfoVo vos) {
        if (vos.getPrizesId() == null) {
            List<ProductOrders> seven = productOrdersService.verify(DateUtils.afterDay("7"), DateUtils.endOfDay(), userId);
            if (seven != null && seven.size() > 0) {
                return "七日内只能兑换一次商品";
            }
        }
        boolean flag = false;

        BigDecimal totalAmount = new BigDecimal("0");
        List<ProductOrderDetails> detailsList = new ArrayList<>();
        for (ProductInfo vo : vos.getProductInfoList()) {
            ProductInfo product = productInfoMapper.selectProductInfoById(vo.getId());
            if (StringUtils.greaterThan(product.getProductQuantity(), vo.getProductQuantity())) {
                //商品库存减一
                product.setProductQuantity(StringUtils.minus(product.getProductQuantity(), vo.getProductQuantity()));
                productInfoMapper.updateProductInfo(product);
                if (StringUtils.isNotBlank(product.getProductCategory()) && "2".equals(product.getProductCategory())) {
                    flag = true;
                    pointsLogService.gainPoints(userId, product.getProductPoints(), "4", "兑换商品");
                } else {
                    //创建订单详情
                    ProductOrderDetails details = new ProductOrderDetails();
                    //商品id
                    details.setProductId(product.getId());
                    //商品数量
                    details.setQuantity(vo.getProductQuantity());
                    //单价
                    details.setPricePerUnit(product.getProductPoints());
                    //小计
                    BigDecimal subtotal = StringUtils.subtotal(product.getProductPoints(), vo.getProductQuantity());
                    totalAmount = totalAmount.add(subtotal);
                    details.setSubtotal(subtotal.toString());
                    detailsList.add(details);
                }
            } else {
                return "商品" + product.getProductName() + "库存不足兑换失败";
            }
        }
        String ordersType = "0";
        if (vos.getPrizesId() != null) {
            SysUserPrizes prizes = prizesMapper.selectSysUserPrizesById(vos.getPrizesId());
            prizes.setPrizesStatus("1");
            ordersType = "1";
            prizesMapper.updateSysUserPrizes(prizes);
        } else {
            //抠除用户积分
            int a = pointsLogService.losePoints(userId, totalAmount.toString(), "4", "兑换商品");
            if (a == 0) {
                return "积分不足兑换失败";
            }
        }
        if (!flag) {
            //创建订单
            ProductOrders orders = new ProductOrders();
            orders.setUserId(userId);
            orders.setAddressId(vos.getConsigneeInfoId());
            orders.setTotalAmount(totalAmount);
            orders.setPaymentStatus("0");
            orders.setShippingStatus("0");
            orders.setOrdersType(ordersType);
            orders.setOrderNumber(System.currentTimeMillis());
            orders.setProductOrderDetailsList(detailsList);
            orders.setCreateTime(DateUtils.getNowDate());
            productOrdersService.insertProductOrders(orders);
        }
        return "兑换成功";
    }

    @Override
    public List<PrizeProductInfo> prizeDrawProductList(Long id) {
        List<PrizeProductInfo> productInfoList = productInfoMapper.selectPrizeDrawRuleProductInfoList(id);
        PrizeProductInfo thanks = productInfoMapper.selectThanks();
        productInfoList.add(thanks);
        return productInfoList;
    }

    @Transactional
    @Override
    public AjaxResult purchaseProduct(Long userId, ProductInfoVo vos) {
        BigDecimal totalAmount = new BigDecimal("0");
        List<ProductOrderDetails> detailsList = new ArrayList<>();
        String sub = "";
        String body = "";
        for (ProductInfo vo : vos.getProductInfoList()) {
            ProductInfo product = productInfoMapper.selectProductInfoById(vo.getId());
            if (StringUtils.greaterThan(product.getProductQuantity(), vo.getProductQuantity())) {
                //商品库存减一
                product.setProductQuantity(StringUtils.minus(product.getProductQuantity(), vo.getProductQuantity()));
                productInfoMapper.updateProductInfo(product);
                //创建订单详情
                ProductOrderDetails details = new ProductOrderDetails();
                //商品id
                details.setProductId(product.getId());
                //商品数量
                details.setQuantity(vo.getProductQuantity());
                //单价
                details.setPricePerUnit(product.getProductAmount());
                //小计
                BigDecimal subtotal = StringUtils.subtotal(product.getProductAmount(), vo.getProductQuantity());
                totalAmount = totalAmount.add(subtotal);
                details.setSubtotal(subtotal.toString());
                detailsList.add(details);
            } else {

                return AjaxResult.error("商品" + product.getProductName() + "库存不足兑换失败");
            }
            sub = product.getProductName();
            body = product.getProductRemark();
        }
        String ordersType = "0";
        //创建订单
        ProductOrders orders = new ProductOrders();
        orders.setUserId(userId);
        orders.setAddressId(vos.getConsigneeInfoId());
        orders.setTotalAmount(totalAmount);
        orders.setPaymentStatus("0");
        orders.setShippingStatus("0");
        orders.setOrdersType(ordersType);
        orders.setOrderNumber(System.currentTimeMillis());
        orders.setProductOrderDetailsList(detailsList);
        orders.setCreateTime(DateUtils.getNowDate());
        productOrdersService.insertProductOrders(orders);
        try {
            if ("1".equals(vos.getPayForType())) {
                AliPayUtil aliPayUtil = new AliPayUtil();
                AlipayClient client = aliPayUtil.init(endpoint, appid, privateKey, alipayPublicKey);
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(body);
                model.setTimeoutExpress("30m");
                model.setOutTradeNo(orders.getOrderNumber() + "");
                model.setTotalAmount(totalAmount + "");
                model.setSubject(sub);
                request.setBizModel(model);
                request.setNotifyUrl("http://taishanbaitai.com:9257/system/pay/aliPayCallback");
                AlipayTradeAppPayResponse response = client.sdkExecute(request);
                return AjaxResult.success(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处
            } else if ("2".equals(vos.getPayForType())) {
                //todo 微信支付
                return AjaxResult.error("暂未开放");
            }
            return AjaxResult.error("请选择正确的支付渠道");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("购买失败");
        }

    }
}
